package com.client.window;

import com.client.service.OICQClient;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;

public class ChatWindow extends JFrame {
    private JTextArea chatArea;
    private JTextField messageField;
    private JButton sendButton;
    private OICQClient client;
    private String friendName;
    private int friendId; // 添加friendId变量

    public ChatWindow(OICQClient client, String friendName, int friendId, String latestMessage, MainWindow mainWindow) { // 修改构造函数
        this.client = client;
        this.friendName = friendName;
        this.friendId = friendId; // 初始化friendId
        setTitle("与 " + friendName + " 聊天");
        setSize(400, 300);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setLocationRelativeTo(null);

        JPanel panel = new JPanel(new BorderLayout());
        add(panel);

        chatArea = new JTextArea();
        chatArea.setEditable(false);
        panel.add(new JScrollPane(chatArea), BorderLayout.CENTER);

        JPanel inputPanel = new JPanel(new BorderLayout());
        messageField = new JTextField();
        sendButton = new JButton("发送");
        inputPanel.add(messageField, BorderLayout.CENTER);
        inputPanel.add(sendButton, BorderLayout.EAST);
        panel.add(inputPanel, BorderLayout.SOUTH);

        sendButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String message = messageField.getText();
                if (!message.isEmpty()) {
                    chatArea.append("我: " + message + "\n");
                    messageField.setText("");
                    try {
                        client.sendMessage(friendId, message); // 使用friendId
                        //client.saveMessage(client.getUserId(), friendId, message); // 保存消息到客户端本地数据库
                    } catch (IOException ex) {
                        ex.printStackTrace();
                        JOptionPane.showMessageDialog(null, "消息发送失败");
                    }
                }
            }
        });

        // 添加窗口关闭监听器
        addWindowListener(new java.awt.event.WindowAdapter() {
            @Override
            public void windowClosed(java.awt.event.WindowEvent e) {
                mainWindow.removeOpenChatWindow(friendId);
            }
        });

        // 将窗口添加到 MainWindow 的 Map 中
        mainWindow.addOpenChatWindow(friendId, this);

        if (latestMessage != null && !latestMessage.isEmpty()) {
            chatArea.append(friendName + ": " + latestMessage + "\n");
        }

        setVisible(true);
    }

    public void receiveMessage(String message) {
        SwingUtilities.invokeLater(() -> {
            chatArea.append(friendName + ": " + message + "\n");
        });
    }
}
